﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace TextBook
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuItem_Open_Click(object sender, RoutedEventArgs e)
        {
            var f = new OpenFileDialog();
            f.CheckFileExists = true;
            f.Filter = "TXT 文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Split(f.FileName);
            }
        }



        private void Split(string file)
        {
            string txt = string.Empty;
            using (var sm = new StreamReader(file, Encoding.Default))
            {
                txt = sm.ReadToEnd();
            }

            S(txt);
        }

        private void S(string sm)
        {
            string parten = @"^.{0,10}[第0-9零一二三四五六七八九十百千万章]{3,}.{1,20}$";
            var reg = new Regex(parten, RegexOptions.Multiline);

            var match = reg.Match(sm);

            var data = new List<TextItem>();

            while (match.Success)
            {
                var old = match;
                match = match.NextMatch();

                var title = sm.Substring(old.Index, old.Length);
                var body = string.Empty;

                var start = old.Index + old.Length + 1;
                if (match.Success)
                {
                    body = sm.Substring(start, match.Index - start);
                }
                else
                {
                    body = sm.Substring(start);
                }

                if (!string.IsNullOrWhiteSpace(body))
                {
                    data.Add(new TextItem { Title = title, Body = body });
                }
            }
            dgvTxt.ItemsSource = data;

        }

        private void MenuItem_Save_Click(object sender, RoutedEventArgs e)
        {

        }

        private void MenuItem_Exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
